package java8.xml.dom4j.xPath;

import org.dom4j.*;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;

/**
 * @author 周宇
 * @create 2020-08-28 11:46
 */
public class XPathTest {
    public static void main(String[] args) throws Exception {
        SAXReader reader = new SAXReader();
        Document document = reader.read(new File("src/main/resources/xml/students2.xml"));

        // 选择所有的student元素
        List<Node> list = document.selectNodes("//Students");
        list.forEach(o -> {
            System.out.println("==1==" + o.getStringValue());
        });

        // 选择文本内容是"张三"的name元素
        Element name = (Element) document.selectSingleNode("//name[text()='张三']");
        System.out.println("==2==" + name.getName() + " " + name.getText());

        // 选择所有id属性节点
        List<Node> list2 = document.selectNodes("//@id");
        list2.forEach(o -> {
            System.out.println("==3==" + o.getName() + " " + o.getStringValue());
        });

        // 选择id属性为002的student元素
        Element student = (Element) document.selectSingleNode("//student[@id='002']");
        Attribute attr = student.attribute("id");
        System.out.println("==4==" + attr.getName() + " " + attr.getValue());

        //选择根元素节点的所有子节点
        Element root = document.getRootElement();
        List<Node> list3 = document.selectNodes("/Students/*");
        list3.forEach(o -> {
            System.out.println("==5==" + o.getStringValue());
        });
    }
}
